import { DB } from '~/server/db.ts'
import Moment from 'moment'
DB.note.belongsTo(DB.user)
DB.comment.belongsTo(DB.user)
DB.reply.belongsTo(DB.comment)
DB.note.hasMany(DB.comment)
export default defineEventHandler(async (event) => {
  const query = getQuery(event)
  let {
    id: noteId, userId = ''
  } = query
  const note = await DB.note.findOne({
    where: {
      id: noteId
    },
    include: [{
      model: DB.user,
      attributes: ['id', 'name', 'avatar']
    }, {
      model: DB.comment,
      include: [
        {
          model: DB.user,
          attributes: ['id', 'avatar', 'name']
        }
      ]
    }
    ]
  })
  if(!note) return {
    code: 404,
    msg: '不存在该笔记！'
  }
  // 加载回复
  let msg = 0 // 消息数量
  for (let commentItem of note.comments) {
    msg++
    const replies = await DB.reply.findAll({
      where: {
        commentId: commentItem.get('id'),
        status: 1 // 审核通过
      }
    })
    for (let row of replies) {
      msg++
      let userId = row.get('userId')
      let replyUserId = row.get('replyUserId')
      // 回复用户
      let user = await DB.user.findByPk(userId, {
        attributes: ['id', 'avatar', 'name']
      })
      // 被回复用户
      let replyUser = await DB.user.findByPk(replyUserId, {
        attributes: ['id', 'avatar', 'name']
      })
      row.dataValues.user = user
      row.dataValues.replyUser = replyUser
    }
    commentItem.dataValues.replies = replies
  }
  note.dataValues.msg = msg
  const isLike = await DB.like.findOne({
    where: {
      noteId,
      userId
    }
  })
  const isFavorite = await DB.favorite.findOne({
    where: {
      noteId,
      userId
    }
  })
  note.dataValues.isLike = isLike ? true : false
  note.dataValues.isFavorite = isFavorite ? true : false
  if (note.userId != userId) { // 不能自己关注自己
    const isFocus = await DB.fans.findOne({
      where: {
        userId: note.userId,
        fansId: userId
      }
    })
    note.dataValues.isFocus = isFocus ? true : false
  }
  // 增加话题浏览量
  for (let row of note.topic) {
    const [item, created] = await DB.topic.findOrCreate({
      where: { name: row.trim() },
      defaults: {
        browse: 1,
        createdAt: Moment().format('YYYY-MM-DD HH:mm:ss'),
        updatedAt: Moment().format('YYYY-MM-DD HH:mm:ss')
      }
    })
    if (!created) {
      item.browse++
      item.updatedAt = Moment().format('YYYY-MM-DD HH:mm:ss')
      await item.save()
    }
  }
  // 增加笔记浏览量
  note.browse++
  await note.save()
  return {
    code: 200,
    msg: 'success',
    data: note
  }
})
